package com.bodacn.keypoint;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class AttendActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int MSG_GetAttendMaOver = 1001;
    public static final int MSG_ERRMSG = 1003;
    public static final int MSG_SaveTransOver = 1004;
    public static final int MSG_GetAttendTotalOver=1005;
    public static final int MSG_ReGetData=1006;

    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    SQLiteDatabase mainDB;

    //全局提示;
    Toast curToast;
    private ProgressDialog waitDialog = null;
    //布局元素;
    ListView masterList,detailList;
    EditText edit_workDate;
    TextView tv_attendState,total_WorkLong2;
    EditText view_numEdit,edit_debug;
    Button view_oneBtn,view_twoBtn,view_threeBtn,view_fourBtn,view_fiveBtn,
            view_sixBtn,view_sevenBtn,view_eightBtn,view_nineBtn,view_zeroBtn,
            view_pointBtn,view_delBtn,view_clrBtn,view_okBtn;
    Button btn_Reset;

    //全局变量
    String curLoginUserNo,curLoginUser,serviceUrl="",curDepartNo="",curDepart="",
            curKeyID="",curOrderNo ="",  curRptStyleNo ="",curStyleNo ="",curStyleSort="",curFactory="";//操作员所属部门等信息;
    String CPUID="",curServiceUrl="",curServiceDir="",WorkSection="SEW";
    boolean overWriteSign,dataEditSign=false;
    //当前选中的内容;
    private int selRowIndex=-1,selDeRowIndex=-1;//当前选中的行;
    private JSONArray masterJSON,resultJson,detailJSON;
    String BatchID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //启动Activity
        setContentView(R.layout.activity_attend);
        hideBottomUIMenu();

        //创建对话框，
        waitDialog=new ProgressDialog(this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curFactory=paramBundle.getString("CurFactory");
        curOrderNo=paramBundle.getString("CurOrderNo");
        curRptStyleNo=paramBundle.getString("CurRptStyleNo");
        curStyleNo=paramBundle.getString("CurStyleNo");
        curStyleSort=paramBundle.getString("CurStyleSort");
        curKeyID=paramBundle.getString("CurKeyID");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        WorkSection=paramBundle.getString("WorkSection","SEW");
        CPUID=paramBundle.getString("CPUID");
        System.out.println(paramBundle);
        //初始化按键，并将页面加载到fragment列表中;
        InitView();
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        findViewById(R.id.btn_find).postDelayed(new Runnable() {
            public void run() {
                refreshAttendMaList(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
                refreshAttendDeList(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
                refreshAttendTotal(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
            }
        }, 500);
    }



    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }


    // /判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    private void InitView() {
        total_WorkLong2=findViewById(R.id.total_WorkLong2);
        btn_Reset=findViewById(R.id.btn_Reset);
        btn_Reset.setOnClickListener(this);
        //文本框
        edit_workDate = (EditText) findViewById(R.id.edit_workDate);
        edit_workDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(v.getContext(), null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,getString(R.string.Finish),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edit_workDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,getString(R.string.Cancel),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle(getString(R.string.PleaseSelectQueryDate));
                mDialog.show();

            }
        });
        edit_workDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        detailList=findViewById(R.id.detailList);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                //置选择制单信息;
                try {
                    selDeRowIndex=position;
                    overWriteSign=true;
                    view_numEdit.setText(detailJSON.optJSONObject(position).getString("WorkLong2"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        //表格
        masterList =(ListView)findViewById(R.id.masterList);
        masterList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                view.setSelected(true);
                //置选择制单信息;
                try {
                    selRowIndex=position;
                    selDeRowIndex=-1;
                    getEmpDetail(masterJSON.optJSONObject(position).getString("EmpNo"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        System.out.println("ViewFragment..............................3");
        findViewById(R.id.btn_find).setOnClickListener(this);
        findViewById(R.id.btn_saveData).setOnClickListener(this);
        findViewById(R.id.btn_submitState).setOnClickListener(this);
        findViewById(R.id.btn_cancelState).setOnClickListener(this);
        findViewById(R.id.btn_Close).setOnClickListener(this);
        tv_attendState=findViewById(R.id.tv_attendState);
        //界面显示
        view_numEdit=(EditText)findViewById(R.id.view_numEdit);
        view_numEdit.setInputType(InputType.TYPE_NULL);
        edit_debug=(EditText)findViewById(R.id.edit_debug);
        System.out.println("ViewFragment..............................4");
        //界面按键
        view_oneBtn=(Button)findViewById(R.id.view_oneBtn);
        view_oneBtn.setOnClickListener(this);
        view_twoBtn=(Button)findViewById(R.id.view_twoBtn);
        view_twoBtn.setOnClickListener(this);
        view_threeBtn=(Button)findViewById(R.id.view_threeBtn);
        view_threeBtn.setOnClickListener(this);
        view_fourBtn=(Button)findViewById(R.id.view_fourBtn);
        view_fourBtn.setOnClickListener(this);
        view_fiveBtn=(Button)findViewById(R.id.view_fiveBtn);
        view_fiveBtn.setOnClickListener(this);
        view_sixBtn=(Button)findViewById(R.id.view_sixBtn);
        view_sixBtn.setOnClickListener(this);
        view_sevenBtn=(Button)findViewById(R.id.view_sevenBtn);
        view_sevenBtn.setOnClickListener(this);
        view_eightBtn=(Button)findViewById(R.id.view_eightBtn);
        view_eightBtn.setOnClickListener(this);
        view_nineBtn=(Button)findViewById(R.id.view_nineBtn);
        view_nineBtn.setOnClickListener(this);
        view_zeroBtn=(Button)findViewById(R.id.view_zeroBtn);
        view_zeroBtn.setOnClickListener(this);
        view_pointBtn=(Button)findViewById(R.id.view_pointBtn);
        view_pointBtn.setOnClickListener(this);
        view_delBtn=(Button)findViewById(R.id.view_delBtn);
        view_delBtn.setOnClickListener(this);
        view_clrBtn=(Button)findViewById(R.id.view_clrBtn);
        view_clrBtn.setOnClickListener(this);
        view_okBtn=(Button)findViewById(R.id.view_okBtn);
        view_okBtn.setOnClickListener(this);

        System.out.println("ViewFragment..............................5");
        //初始提醒;
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String StartDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime() -1 * 24 * 60 * 60 * 1000));
        edit_workDate.setText(StartDateStr);
        curToast = Toast.makeText(this, getString(R.string.SystemHint), Toast.LENGTH_LONG);

    }

    private void getEmpDetail(String empNo) {
        try {
            detailJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Cursor cursor=mainDB.rawQuery("Select * from AttendDe where EmpNo=?",new String[]{empNo});
        while (cursor.moveToNext()){
            JSONObject jsonObject=new JSONObject();
            try {
                jsonObject.put("KeyID",cursor.getString(cursor.getColumnIndex("KeyID")));
                jsonObject.put("ManuDepart",cursor.getString(cursor.getColumnIndex("ManuDepart")));
                jsonObject.put("EmpNo",cursor.getString(cursor.getColumnIndex("EmpNo")));
                jsonObject.put("WorkLong1",cursor.getFloat(cursor.getColumnIndex("WorkLong1")));
                jsonObject.put("WorkLong2",cursor.getFloat(cursor.getColumnIndex("WorkLong2")));
                detailJSON.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        DetailListAdapter detailListAdapter=new DetailListAdapter(detailList.getContext());
        detailList.setAdapter(detailListAdapter);
        CalceSumWorkLong2();
    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    @Override
    public void onClick(View v) {
        AlertDialog alertDialog;
        switch (v.getId())
        {
            case R.id.btn_Reset:
                resetData(curDepart,edit_workDate.getText().toString());
                break;
            case R.id.btn_find:
                refreshAttendMaList(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
                refreshAttendDeList(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
                break;
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                if (selDeRowIndex<0){
                    curToast.setText("请选择要修改的明细行!");
                    curToast.show();
                    return;
                }
                Button tmpBtn1=(Button)v.findViewById(v.getId());
                if (overWriteSign==true) {
                    view_numEdit.setText(tmpBtn1.getText());
                    overWriteSign=false;
                } else {
                    if ((view_numEdit.getText().toString().indexOf(".") == -1)&&(view_numEdit.getText().toString().indexOf("/") == -1)) {
                        view_numEdit.getText().append(tmpBtn1.getText());
                    } else {
                        if (view_numEdit.getText().toString().indexOf(".5")==-1) {
                            if (tmpBtn1.getText().toString().equals("5"))
                                view_numEdit.getText().append(tmpBtn1.getText());
                            else {
                                curToast.setText("小数点后只能输入5,请注意!");
                                curToast.show();
                            }
                        } else {
                            curToast.setText("只能有一位小数,请注意!");
                            curToast.show();
                        }
                    }

                }
                if (view_numEdit.getText().toString().length()>0) updateNumber(Float.parseFloat(view_numEdit.getText().toString()));
                else  updateNumber(0);
                break;
            case R.id.view_delBtn:
                if (selDeRowIndex<0){
                    curToast.setText("请选择要修改的明细行!");
                    curToast.show();
                    return;
                }
                if (view_numEdit.getText().length()>0)
                {
                    overWriteSign=false;
                    view_numEdit.setSelection(view_numEdit.getText().length());
                    System.out.println(view_numEdit.getSelectionStart());
                    int start=view_numEdit.getSelectionStart();
                    view_numEdit.getText().delete(start-1,start);
                }
                if (view_numEdit.getText().toString().length()>0) updateNumber(Float.parseFloat(view_numEdit.getText().toString()));
                else  updateNumber(0);
                break;
            case R.id.view_pointBtn:
                if (selDeRowIndex<0){
                    curToast.setText("请选择要修改的明细行!");
                    curToast.show();
                    return;
                }
                System.out.println("AindexOf:" + view_numEdit.getText().toString().indexOf("."));
                if ((view_numEdit.getText().toString().indexOf(".") == -1)&&(view_numEdit.getText().toString().indexOf("/") == -1)) {
                    view_numEdit.getText().append(".");
                }
                break;

            case R.id.btn_saveData:
                //调用存储过程刷新数据;
                alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("您确定要保存记录吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                saveData(curDepart,edit_workDate.getText().toString());
                            }
                        }).setNeutralButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                break;
            case R.id.view_clrBtn:
                if (selDeRowIndex<0){
                    curToast.setText("请选择要修改的明细行!");
                    curToast.show();
                    return;
                }
                view_numEdit.setText("");
                updateNumber(0);
                break;
            case R.id.view_okBtn:
                if (selDeRowIndex>=0&&selRowIndex>=0){
                    float totalLong=0;
                    try {
                        for (int i=0;i<detailJSON.length();i++){
                            totalLong=(float) (totalLong+ detailJSON.optJSONObject(i).getDouble("WorkLong2"));
                        }
                        System.out.println(String.format("totalLong  %.2f",totalLong));
                        System.out.println(String.format("WorkLong2  %.2f",masterJSON.optJSONObject(selRowIndex).getDouble("WorkLong2")));

                        if (String.format("%.2f", totalLong).equals(String.format("%.2f",masterJSON.optJSONObject(selRowIndex).getDouble("WorkLong2")))){
                            //masterJSON.optJSONObject(selRowIndex).put("WorkLong2",totalLong);
                            for (int i=0;i<detailJSON.length();i++){
                                mainDB.execSQL("Update AttendDe Set WorkLong2=? where EmpNo=? and ManuDepart=?",
                                        new Object[]{detailJSON.optJSONObject(i).getDouble("WorkLong2"),
                                                detailJSON.optJSONObject(i).getString("EmpNo"),
                                                detailJSON.optJSONObject(i).getString("ManuDepart")});;
                            }
                            curToast.setText("保存分配工时成功!");
                            curToast.show();
                        } else {
                            alertDialog = new AlertDialog.Builder(v.getContext())
                                    .setTitle("系统提示").setMessage("工时分配值与出勤工时不符,请检查！")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).create(); // 创建对话框
                            alertDialog.show(); // 显示对话框
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_Close:
                alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("你确定要关闭当前窗口？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).setNeutralButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                break;
            case R.id.btn_submitState:
                //调用存储过程刷新数据;
                alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("您确定要将"+edit_workDate.getText().toString()+"出勤记录转为提交状态吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                AttendDeSaveTrans("Submit",curDepart,edit_workDate.getText().toString(),BatchID);
                            }
                        }).setNeutralButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                break;
            case R.id.btn_cancelState:
                //调用存储过程刷新数据;
                alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("您确定要将"+edit_workDate.getText().toString()+"出勤记录撤回提交吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                AttendDeSaveTrans("Cancel",curDepart,edit_workDate.getText().toString(),BatchID);
                            }
                        }).setNeutralButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                break;
            default:
                break;
        }
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void saveData(final String paramDepart,  final String paramWorkDate){
        if (masterJSON == null || masterJSON.length()==0) return;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into SceneAttendDe(AttendDeID,BatchID,CurDepart,WorkDate,EmpNo,ManuDepart,WorkLong1,WorkLong2) values(newid(),?,?,?,?,?,?,?)");
                    //增加明细表
                    Cursor cur=mainDB.rawQuery("Select * from AttendDe",null);
                    while (cur.moveToNext()){
                        pstmt.setString(1, BatchID);
                        pstmt.setString(2, paramDepart);
                        pstmt.setString(3, paramWorkDate);
                        pstmt.setString(4, cur.getString(cur.getColumnIndex("EmpNo")));
                        pstmt.setString(5,cur.getString(cur.getColumnIndex("ManuDepart")));
                        pstmt.setString(6, cur.getString(cur.getColumnIndex("WorkLong1")));
                        pstmt.setString(7, cur.getString(cur.getColumnIndex("WorkLong2")));
                        pstmt.executeUpdate();
                    }
                    pstmt.close();
                    //调用存储过程;
                    //调用存储过程;
                    SqlComm = " Exec SceneAttendDeSaveTrans @OperType='SaveTrans',@WorkDate='"+paramWorkDate+"',@Depart='" + paramDepart+"',@BatchID='" + BatchID+"',@UserNo='" + curLoginUserNo+"',@UserName='" + curLoginUser + "'";
                    ReadSQLData(SqlComm);

                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }

    private void updateNumber(float paramNumber){
        if (selDeRowIndex>=0){
            if (detailJSON !=null)
            {
                try {
                    dataEditSign=true;
                    detailJSON.getJSONObject(selDeRowIndex).put("WorkLong2",paramNumber);
                    //更新显示;
                    ((BaseAdapter) detailList.getAdapter()).notifyDataSetChanged();
                    CalceSumWorkLong2();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    //刷新工序列表;
    private void resetData(final String paramDepart, final String paramDate, final String paramUserNo)
    {

        //执行SQL过程
        String SqlComm = "Exec AttendEmpQuery  @OperType='GetAttendMa',@Department='"
                + paramDepart+ "',@WorkDate='" + paramDate+ "',@WorkSection='" + WorkSection+ "',@UserNo='" + paramUserNo+ "'";
        //调用WebService过程并处理界面更新;
        Log.d("msg", "serviceUrl------------------" + serviceUrl);
        ReadSQLData(SqlComm);
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void resetData(final String paramDepart, final String paramDate)
    {
        if (masterJSON == null || masterJSON.length()==0) return;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Exec AttendEmpQuery  @Recdate=?,@Department=?");
                    pstmt.setString(1, paramDate);
                    pstmt.setString(2, paramDepart);
                    pstmt.executeUpdate();
                    pstmt.close();
                    //显示预排单;
                    Message msg = new Message();
                    msg.what = MSG_ReGetData;
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }

    //刷新工序列表;
    private void refreshAttendMaList(final String paramDepart, final String paramDate, final String paramUserNo)
    {
        try {
            masterJSON=new JSONArray("[]");
            MasterListAdapter masterListAdapter=new MasterListAdapter(masterList.getContext());
            masterList.setAdapter(masterListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BatchID = java.util.UUID.randomUUID().toString();
        mainDB.execSQL("Delete from AttendDe");
        selRowIndex = -1;
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        //执行SQL过程
        String SqlComm = "Exec ScenePAD_GetAttend  @OperType='GetAttendMa',@Department='"
                + paramDepart+ "',@WorkDate='" + paramDate+ "',@WorkSection='" + WorkSection+ "',@UserNo='" + paramUserNo+ "'";
        //调用WebService过程并处理界面更新;
        Log.d("msg", "serviceUrl------------------" + serviceUrl);
        ReadSQLData(SqlComm);
    }


    //刷新工序列表;
    private void refreshAttendDeList(final String paramDepart, final String paramDate, final String paramUserNo)
    {
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        //执行SQL过程
        String SqlComm = "Exec ScenePAD_GetAttend  @OperType='GetAttendDe',@Department='"
                + paramDepart+ "',@WorkDate='" + paramDate+ "',@WorkSection='" + WorkSection+ "',@UserNo='" + paramUserNo+ "'";
        //调用WebService过程并处理界面更新;
        Log.d("msg", "serviceUrl------------------" + serviceUrl);
        ReadSQLData(SqlComm);
    }
    //刷新工序列表;
    private void refreshAttendTotal(final String paramDepart, final String paramDate, final String paramUserNo)
    {
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        //执行SQL过程
        String SqlComm = "Exec ScenePAD_GetAttend  @OperType='AttendTotal',@Department='"
                + paramDepart+ "',@WorkDate='" + paramDate+ "',@WorkSection='" + WorkSection+ "',@UserNo='" + paramUserNo+ "'";
        //调用WebService过程并处理界面更新;
        Log.d("msg", "serviceUrl------------------" + serviceUrl);
        ReadSQLData(SqlComm);
    }

    //刷新工序列表;
    private void AttendDeSaveTrans(final String paramOperType,final String paramDepart, final String paramDate,final String paramBatchID)
    {
        waitDialog.setMessage(getString(R.string.WaitingFromNetGetData));
        waitDialog.show();
        //调用存储过程;
        String SqlComm = " Exec SceneAttendDeSaveTrans @OperType='"+paramOperType+"',@WorkDate='"+paramDate+"',@Depart='" + paramDepart+"',@BatchID='" + paramBatchID+"',@UserNo='" + curLoginUserNo+"',@UserName='" + curLoginUser + "'";
        ReadSQLData(SqlComm);
    }


    //检查数据,报数不能超过今日检验数
    private boolean CalceSumWorkLong2() {
        total_WorkLong2.setText("0");
        if (detailJSON == null) return false;
        if (detailJSON.length() > 0) {
            float targetValue=0;
            for (int i = 0; i< detailJSON.length(); i++){
                try {
                    targetValue= (float) (targetValue+ detailJSON.optJSONObject(i).getDouble("WorkLong2"));
                    total_WorkLong2.setText(String.valueOf(targetValue));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;

    }



    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println(SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)){
                        if (jsonArray.optJSONObject(0).has("OperType")==true)  OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)  OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");

                        //返回的为状态数据;
                        if (OperType.equals("GetAttendMa"))
                        {
                            Log.d("msg","GetDaliyCount--------------------2");
                            masterJSON =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_GetAttendMaOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        //返回的为状态数据;
                        if (OperType.equals("AttendTotal"))
                        {
                            Log.d("msg","AttendTotal--------------------2");
                            resultJson =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_GetAttendTotalOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                        if (OperType.equals("GetAttendDe"))
                        {
                            Log.d("msg","GetGetAttendDe--------------------2");
                            //插入数据
                            String KeyID="",EmpNo="",ManuDepart="";
                            float WorkLong1=0,WorkLong2=0;
                            mainDB.execSQL("Delete from AttendDe");
                            for (int i=0;i<jsonArray.length();i++){
                                if (jsonArray.optJSONObject(i).has("KeyID")) KeyID=jsonArray.optJSONObject(i).getString("KeyID");
                                if (jsonArray.optJSONObject(i).has("EmpNo")) EmpNo=jsonArray.optJSONObject(i).getString("EmpNo");
                                if (jsonArray.optJSONObject(i).has("ManuDepart")) ManuDepart=jsonArray.optJSONObject(i).getString("ManuDepart");
                                if (jsonArray.optJSONObject(i).has("WorkLong1")) WorkLong1=(float)jsonArray.optJSONObject(i).getDouble("WorkLong1");
                                if (jsonArray.optJSONObject(i).has("WorkLong2")) WorkLong2=(float)jsonArray.optJSONObject(i).getDouble("WorkLong2");
                                mainDB.execSQL("insert into AttendDe(KeyID,EmpNo,ManuDepart,WorkLong1,WorkLong2) " +
                                        "values(?,?,?,?,?)",new Object[]{KeyID,EmpNo,ManuDepart,WorkLong1,WorkLong2});
                            }
                        }

                        if (OperType.equals("SaveTrans")||OperType.equals("Submit")||OperType.equals("Cancel"))
                        {
                            Log.d("msg","MSG_SaveTransOver--------------------2");
                            resultJson =jsonArray;
                            //显示预排单;
                            Message msg = new Message();
                            msg.what = MSG_SaveTransOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                        if (jsonArray.optJSONObject(0).has("ErrInfo")==true)
                        {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("ErrInfo"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }
                        //SQL异常;
                        if (jsonArray.optJSONObject(0).has("SQLExcept")==true)  {
                            //关闭ProgressDialog
                            Message msg = new Message();
                            msg.what = MSG_ERRMSG;
                            Bundle bundle=new Bundle();
                            bundle.putString("MSG",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            msg.setData(bundle);
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            return;
                        }

                    } else{
                        //关闭ProgressDialog
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle=new Bundle();
                        bundle.putString("MSG","未返回数据");
                        msg.setData(bundle);
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //关闭ProgressDialog
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle=new Bundle();
                    bundle.putString("MSG",e.getMessage());
                    msg.setData(bundle);
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            }

        };
        new Thread(run).start();

    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                //关闭ProgressDialog
                if (waitDialog.isShowing()) waitDialog.hide();
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_ReGetData:
                        curToast.setText("重置数据完成，准备重新获取数据!");
                        curToast.show();
                        findViewById(R.id.btn_find).postDelayed(new Runnable() {
                            public void run() {
                                refreshAttendMaList(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
                                refreshAttendDeList(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
                                refreshAttendTotal(curDepartNo,edit_workDate.getText().toString(),curLoginUserNo);
                            }
                        }, 200);
                        break;
                    case MSG_GetAttendTotalOver:
                        fillScreen();
                        break;
                    case MSG_GetAttendMaOver:
                        dataEditSign=false;
                        MasterListAdapter masterListAdapter=new MasterListAdapter(masterList.getContext());
                        masterList.setAdapter(masterListAdapter);
                        if (masterJSON.length()>0){
                            if (masterJSON.optJSONObject(0).has("AttendState")){
                                try {
                                    tv_attendState.setText(masterJSON.optJSONObject(0).getString("AttendState"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        break;

                    case MSG_SaveTransOver:
                        if (resultJson!=null&&resultJson.length()>0){
                            AlertDialog alertDialog = new AlertDialog.Builder(masterList.getContext()).
                                    setTitle(getString(R.string.SystemHint)).
                                    setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }).create();
                            if (resultJson.optJSONObject(0).has("AttendState")){
                                try {
                                    tv_attendState.setText(resultJson.optJSONObject(0).getString("AttendState"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (resultJson.optJSONObject(0).has("ResultInfo")) {
                                try {
                                    alertDialog.setMessage(resultJson.optJSONObject(0).getString("ResultInfo"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } else alertDialog.setMessage("保存成功！");
                            alertDialog.show(); // 显示对话框
                        }
                        break;
                    case MSG_ERRMSG:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("MSG"));
                        curToast.show();
                        break;

                    default:
                        break;
                }
            }
        }


    };

    private void fillScreen() {
        if (resultJson!=null&&resultJson.length()>0){
            try {
                if (resultJson.optJSONObject(0).has("WorkRate"))
                    ((TextView)findViewById(R.id.bottom_WorkRate)).setText(resultJson.optJSONObject(0).getString("WorkRate"));
                if (resultJson.optJSONObject(0).has("AvgTime"))
                    ((TextView)findViewById(R.id.bottom_AvgTime)).setText(resultJson.optJSONObject(0).getString("AvgTime"));
                if (resultJson.optJSONObject(0).has("OwenPeople"))
                    ((TextView)findViewById(R.id.bottom_OwenPeople)).setText(resultJson.optJSONObject(0).getString("OwenPeople"));
                if (resultJson.optJSONObject(0).has("TotalTime"))
                    ((TextView)findViewById(R.id.bottom_TotalTime)).setText(resultJson.optJSONObject(0).getString("TotalTime"));
                if (resultJson.optJSONObject(0).has("WorkPeople"))
                    ((TextView)findViewById(R.id.bottom_WorkPeople)).setText(resultJson.optJSONObject(0).getString("WorkPeople"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    //员工状态表格适配器;
    public final class MasterListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public MasterListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return masterJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return masterJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View  conView = inflater.inflate(R.layout.activity_attend_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            int pullVatListHeight=parent.getHeight();
            conView.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,(pullVatListHeight/15)));
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (masterJSON.optJSONObject(position).has("ConColor")){
                    textColor=GetColorValue(masterJSON.optJSONObject(position).getString("ConColor"));
                }

                TextView tv = (TextView) conView.findViewById(R.id.text_view_EmpNo);// 显示文字
                if (masterJSON.optJSONObject(position).has("EmpNo"))
                    tv.setText(masterJSON.optJSONObject(position).get("EmpNo").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.text_view_EmpName);// 显示文字
                if (masterJSON.optJSONObject(position).has("EmpName"))
                    tv.setText(masterJSON.optJSONObject(position).get("EmpName").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.text_view_WorkSign);// 显示文字
                tv.setTextColor(textColor);
                if (masterJSON.optJSONObject(position).has("WorkSign"))
                    tv.setText(masterJSON.optJSONObject(position).get("WorkSign").toString());
                tv = (TextView) conView.findViewById(R.id.text_view_WorkLong1);// 显示文字
                tv.setTextColor(textColor);
                if (masterJSON.optJSONObject(position).has("WorkLong1"))
                    tv.setText(masterJSON.optJSONObject(position).get("WorkLong1").toString());
                tv = (TextView) conView.findViewById(R.id.text_view_WorkLong2);// 显示文字
                tv.setTextColor(Color.BLUE);
                if (masterJSON.optJSONObject(position).has("WorkLong2"))
                    tv.setText(masterJSON.optJSONObject(position).get("WorkLong2").toString());

                tv = (TextView) conView.findViewById(R.id.text_view_StartTime);// 显示文字
                tv.setTextColor(textColor);
                if (masterJSON.optJSONObject(position).has("StartTime"))
                    tv.setText(masterJSON.optJSONObject(position).get("StartTime").toString());
                tv = (TextView) conView.findViewById(R.id.text_view_EndTime);// 显示文字
                tv.setTextColor(textColor);
                if (masterJSON.optJSONObject(position).has("EndTime"))
                    tv.setText(masterJSON.optJSONObject(position).get("EndTime").toString());
                tv = (TextView) conView.findViewById(R.id.text_view_SingleProc);// 显示文字
                tv.setTextColor(textColor);
                if (masterJSON.optJSONObject(position).has("SingleProc")) {
                    tv.setText(masterJSON.optJSONObject(position).get("SingleProc").toString());
                    if (masterJSON.optJSONObject(position).getInt("SingleProc")>0){
                        tv.setBackgroundColor(getResources().getColor(R.color.burlywood));
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","MasterGridAdapter_position:"+position);
            return conView;
        }
    }

    //员工状态表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View  conView = inflater.inflate(R.layout.activity_attend_splithead, null, false);
            int pullVatListWidth=parent.getWidth();
            int pullVatListHeight=parent.getHeight();
            conView.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,(pullVatListHeight/6)));
            int textColor=getResources().getColor(R.color.text_black);
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                if (detailJSON.optJSONObject(position).has("ConColor")){
                    textColor=GetColorValue(detailJSON.optJSONObject(position).getString("ConColor"));
                }

                TextView tv = (TextView) conView.findViewById(R.id.tv_view_ManuDepart);// 显示文字
                if (detailJSON.optJSONObject(position).has("ManuDepart"))
                    tv.setText(detailJSON.optJSONObject(position).get("ManuDepart").toString());
                tv.setTextColor(textColor);
                tv = (TextView) conView.findViewById(R.id.tv_view_WorkLong1);// 显示文字
                tv.setTextColor(textColor);
                if (detailJSON.optJSONObject(position).has("WorkLong1"))
                    tv.setText(String.format("%.2f",detailJSON.optJSONObject(position).get("WorkLong1")));
                tv = (TextView) conView.findViewById(R.id.tv_view_WorkLong2);// 显示文字
                tv.setTextColor(Color.BLUE);
                if (detailJSON.optJSONObject(position).has("WorkLong2"))
                    tv.setText(String.format("%.2f",detailJSON.optJSONObject(position).get("WorkLong2")));


            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            Log.d("msg","MasterGridAdapter_position:"+position);
            return conView;
        }
    }
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

}
